﻿var zonePreview = function ($) {
    var settings = {
        requestUrl: "/Ajax/News/ZonePreview.aspx",
        contentPlaceHolderElement: '#divOverview'
    };
    var cache = new Array();
    var isLoading = false;

    function buildCacheKey(functionName, args) {
        return String.format("{0}_{1}", functionName, args.join('_'));
    }

    function preview(zoneUrl, callback) {
        if (!isLoading) {
            var cacheKey = buildCacheKey("preview", [zoneUrl]);
            var data = cache[cacheKey];
            if (data != null) {
                display(data, callback);
                return;
            }
            isLoading = true;
            $.ajax({
                url: settings.requestUrl,
                data: { catUrl: zoneUrl },
                success: function (html) {
                    cache[cacheKey] = html;
                    display(html, callback);
                    isLoading = false;
                }
            });
        }
    }

    function execCallback(callback) {
        if (typeof callback == "function")
            return callback();
        return false;
    }

    function display(html, callback) {
        $(settings.contentPlaceHolderElement).html(html).stop(true,true).fadeIn();
        execCallback(callback);
    }

    function close(callback) {
        $(settings.contentPlaceHolderElement).stop(true,true).fadeOut('fast');
        execCallback(callback);
    }

    return {
        init: function (options) {
            $.extend(settings, options);
        },
        preview: function (zoneUrl, callback) {
            return preview(zoneUrl, callback);
        },
        close: function (callback) {
            return close(callback);
        }
    };
} (jQuery);


